﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using ALS.Communication.Contract;
using ALS.Communication.Contract.Enums;
using ALS.Communication.Domain.Commends;
using ALS.Component.Tools.AsyncTcp;
using ALS.Component.Tools.Helpers;

namespace ALS.Communication.Domain.Adapters
{
    /// <summary>
    /// 服务器命令适配器
    /// </summary>
    public class ServerCmdAdapter : IAdapter
    {
        private const string serviceNameSpace = "ALS.Communication.Domain.Commends.{0}Cmd";
        private const byte header = 0x68;
        private const byte commend = (int)CommendTypeEnum.ServerCmd;
        private const byte foot = 0xff;

        public void Process(IEnumerable<byte> datagram, AsyncTcpServer asyncTcpServer, TcpClient tcpClient)
        {
            var address = tcpClient.Client.RemoteEndPoint.ToString().Split('.').Last();
            var request = SerializeHelper.Deserialize<Request>(Encoding.UTF8.GetString(datagram.ToArray()));
            var cmd = (Cmd)Activator.CreateInstance(Type.GetType(string.Format(serviceNameSpace, request.TypeName)));
            var response = cmd.Run(request.RequestBody);
            var bytes = new List<byte>();
            bytes.Add(header);
            bytes.Add(commend);
            bytes.Add((byte)Convert.ToInt32(address, 16));
            bytes.AddRange(Encoding.UTF8.GetBytes(SerializeHelper.Serialize<Response>(response)));
            asyncTcpServer.Send(tcpClient, bytes.ToArray());
        }
    }
}
